#!/bin/bash

# 使用Docker构建RuoYi-TDesign项目的脚本
# 避免在宿主机上安装Node.js和Maven

echo "开始使用Docker构建 RuoYi-TDesign 项目..."

# 创建必要的目录
echo "创建必要的目录..."
sudo mkdir -p /docker/mysql/data /docker/mysql/conf
sudo mkdir -p /docker/redis/data /docker/redis/conf
sudo mkdir -p /docker/minio/data /docker/minio/config
sudo mkdir -p /docker/nginx/cert /docker/nginx/conf.d /docker/nginx/html /docker/nginx/log
sudo mkdir -p /docker/admin/logs /docker/server2/logs /docker/monitor/logs /docker/snailjob/logs

# 启动构建环境容器并构建后端服务
echo "构建后端服务..."
docker run --rm -v "$(pwd)":/app -v ~/.m2:/root/.m2 -w /app maven:3.8.4-openjdk-17 bash -c "
  cd /app/ruoyi-admin &&
  mvn clean package -DskipTests
"

# 构建监控服务
echo "构建监控服务..."
docker run --rm -v "$(pwd)":/app -v ~/.m2:/root/.m2 -w /app maven:3.8.4-openjdk-17 bash -c "
  cd /app/ruoyi-extend/ruoyi-monitor-admin &&
  mvn clean package -DskipTests
"

# 构建任务调度服务
echo "构建任务调度服务..."
docker run --rm -v "$(pwd)":/app -v ~/.m2:/root/.m2 -w /app maven:3.8.4-openjdk-17 bash -c "
  cd /app/ruoyi-extend/ruoyi-snailjob-server &&
  mvn clean package -DskipTests
"

# 使用Node.js Docker镜像构建前端
echo "构建前端服务..."
docker run --rm -v "$(pwd)":/app -w /app node:18 bash -c "
  cd /app/ruoyi-ui &&
  npm config set registry https://registry.npmmirror.com &&
  npm install &&
  npm run build
"

# 构建所有Docker镜像
echo "构建Docker镜像..."

# 构建后端服务镜像
echo "构建 ruoyi-server 镜像..."
cd ruoyi-admin
docker build -t ruoyi/ruoyi-server:1.4.0 .
cd ..

# 构建监控服务镜像
echo "构建 ruoyi-monitor-admin 镜像..."
cd ruoyi-extend/ruoyi-monitor-admin
docker build -t ruoyi/ruoyi-monitor-admin:1.4.0 .
cd ../..

# 构建任务调度服务镜像
echo "构建 ruoyi-snailjob-server 镜像..."
cd ruoyi-extend/ruoyi-snailjob-server
docker build -t ruoyi/ruoyi-snailjob-server:1.4.0 .
cd ../..

# 构建前端服务镜像
echo "构建 ruoyi-ui 镜像..."
cd ruoyi-ui
docker build -t ruoyi/ruoyi-ui:1.4.0 .
cd ..

# 配置Docker镜像加速器
echo "配置Docker镜像加速器..."
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": [
   "https://docker.aityp.com",
    "https://pssdo.dqzboy.xyz"
  ]
}
EOF

# 重启Docker服务
echo "重启Docker服务..."
sudo systemctl daemon-reload
sudo systemctl restart docker

# 启动所有服务
echo "启动所有服务..."
docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d

echo "部署完成！"
echo "查看服务状态: docker-compose ps"
echo "查看日志: docker-compose logs -f"
